<?php
/**
 * Created by PhpStorm.
 * User: zyark
 * Date: 2018/1/12
 * Time: 14:19
 */

namespace app\common\utils;


use OSS\Core\OssException;
use OSS\Http\RequestCore;
use OSS\Http\ResponseCore;
use OSS\OssClient;
use think\Log;

class OssUtils
{
    private $accessKeyId = "LTAIjkupD2LJxeyH";
    private $accessKeySecret = "CJeEa0dVWq32FGQRE58YUz20zXP3Ht";
//    private $endpoint = "oss-cn-beijing.aliyuncs.com";
    private $endpoint = "oss-cn-shenzhen.aliyuncs.com";
//    private $bucket = "ly-school";
    private $bucket = "zyark-live";
    private $ossClient;

    public function getBucket(){
        return $this->bucket;
    }

    public function __construct(){
        $this->ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint,false);
    }

    /**
     * 上传文件
     * @param $object
     * @param $filePath
     * @return mixed
     */
    public function upload($object,$filePath){
        try{
            $this->ossClient->uploadFile($this->bucket, $object, $filePath);
            return array('success'=>true);
        } catch(OssException $e) {
            return array('success'=>false,'error'=>$e->getMessage());
        }
    }

    /**
     * 生成GetObject的签名url,主要用于私有权限下的读访问控制
     * @param $object string 对象
     * @return null
     */
    function getSignedUrlForGettingObject($object)
    {
        $timeout = 3600; // URL的有效期是3600秒
        try{
            $signedUrl = $this->ossClient->signUrl($this->bucket, $object, $timeout);
            /**
             * 可以类似的代码来访问签名的URL，也可以输入到浏览器中去访问
             */
            $request = new RequestCore($signedUrl);
            $request->set_method('GET');
            $request->send_request();
            $res = new ResponseCore($request->get_response_header(), $request->get_response_body(), $request->get_response_code());
            $res = (array)$res;
            return array('success'=>true,'url'=>$res['header']['info']['url']);
        } catch(OssException $e) {
            return array('success'=>false,'error'=>$e->getMessage());
        }

    }

    /**
     * 删除对象
     * @param $object_name
     * @return array
     */
    function deleteObject($object_name){
        try {
            $this->ossClient->deleteObject($this->bucket, $object_name);
            return array('success'=>true);
        } catch (OssException $e) {
            return array('success'=>false,'error'=>$e->getMessage());
        }
    }
}